<?php
require_once __DIR__ . '/../../app/config/config.php';
require_once __DIR__ . '/../Services/OKCoin/OKCoin.php';

const API_KEY = "2d68a3f0-c105-45c5-befe-72412cf6c1b5";
const SECRET_KEY = "7A8441F6B911845CCEB77A6A045FC274";

/**
 * btcusdt 转换为 btc_usd
 * @param $symbol
 * @return mixed
 */
function symbolToUsd($symbol)
{
    if (($suffix = substr($symbol, -4)) != 'usdt') {
        $suffix = substr($symbol, -3);
    }
    $symbol = str_replace($suffix, "_" . $suffix, $symbol);
    return $symbol;
}

function symbolKline($symbol, $period = '30min', $size = 2)
{

    $client = new OKCoin(new OKCoin_ApiKeyAuthentication(API_KEY, SECRET_KEY));

    //获取比特币或莱特币的K线数据
    $params = array('symbol' => symbolToUsd($symbol), 'type' => $period, 'size' => $size, 'contract_type' => 'quarter');

    try {
        // 现货
        $data = $client->klineDataApi($params);
        // 期货
//        $data = $client->futuresKlineDataApi($params);
        if (isset($data->error_code)) {
            return 'url request error.' . $data->error_code;
        }
    } catch (RuntimeException $e) {
        printf("error\t%s\r\n%s\r\n", 'okex', $e->getMessage());
        return 'error';
    }
    $kline = $data[0];
    $default = array(
        'ch' => sprintf("market.%s.kline.%s", $symbol, $period),
        'ts' => $kline[0],
        'tick' => array(
            "id" => $kline[0] / 1000, //时间戳
            "amount" => $kline[5], //交易量
            "count" => 0,
            "open" => $kline[1], //开
            "close" => $kline[4], //收
            "low" => $kline[3], //低
            "high" => $kline[2], //高
            "vol" => 0,
        ),
    );

//    $url = getUrlForKline($default['ch']);
    $url = "http://47.94.163.169/kline_pre5min";

    if ($url == null) {
        return 'kline url is null.';
    }

    try {
        list($head, $body) = httpRequest($url, json_encode($default), 5);
        printf("%s\r\n%s\r\n", $url, $body);

        echo PHP_EOL;
    } catch (RuntimeException $e) {
        printf("error\t%s\r\n%s\r\n", $url, $e->getMessage());
    }

    return $data;
}

function main($period = '30min', $size = 2)
{
    global $SYMBOL_FUTURES;

    $i = $sum = 0;
    foreach (array_unique($SYMBOL_FUTURES) as $symbol) {
        $message = symbolKline($symbol, $period, $size);
        usleep(150);
        $sum++;
    }
    return $sum;
}


$params = getopt('k:s::');

if (isset($params['k']) &&
    in_array($params['k'], ['1min', '5min', '15min', '30min', '60min', '1day', '1mon', '1week', '1year'])) {
    if (isset($params['s'])) {
        $message = symbolKline($params['s'], $params['k']);
    } else {
        $message = main($params['k']);
    }
} else {
    $message = <<<EOF
s: btcusdt,bchusdt...
k: 1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year
EOF;

}
echo $message;
